package cn.hfatec.shms.web.ss.ssCrux.service;

import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.advice.annotation.MysqlDataSourceXm;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.ss.ssCrux.dao.SsCruxDao;
import cn.hfatec.shms.web.ss.ssCrux.model.SsCrux;
import cn.hfatec.shms.web.ss.ssCrux.model.SsCruxParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("SsCruxService")
public class SsCruxService {

    public static final String BEAN_ID = "SsCruxService";

    //注入Dao层
    @Resource(name = "SsCruxDao")
    private SsCruxDao ssCruxDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param ssCruxParams
     * @param page
     */
    @Transactional
    @MysqlDataSource
    public Table querySsCruxTable(SsCruxParams ssCruxParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", ssCruxParams);
        return baseDao.queryTableByPage("querySsCrux", params, page);
    }

    /**
     * 插入数据
     *
     * @param ssCrux
     */
    @Transactional
    @MysqlDataSource
    public void saveSsCrux(SsCrux ssCrux) {
        if (ssCrux.getId() != null) {
            SsCrux result = getSsCrux(ssCrux.getId());
            if (result != null) {
                ssCruxDao.update(ssCrux);
            } else {
                ssCruxDao.insert(ssCrux);
            }
        } else {
            ssCruxDao.insert(ssCrux);
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public void deleteSsCrux(Integer id) {

        ssCruxDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param ssCruxList
     */
    @Transactional
    @MysqlDataSource
    public void deleteSsCruxBatch(List<String> ssCruxList) {
        for (String id : ssCruxList) {
            deleteSsCrux(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public SsCrux getSsCrux(Integer id) {

        return ssCruxDao.getSsCruxById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param cruxId
     */
    @Transactional
    @MysqlDataSource
    public SsCrux getSsCruxCruxId(String cruxId) {

        return ssCruxDao.getSsCruxByCruxId(cruxId);
    }

    /**
     * 根据ID获取数据
     *
     * @param testDate
     * @param testEnd
     */
    @Transactional
    @MysqlDataSourceXm
    public List<SsCrux> selectCrux(String testDate, String testEnd) {

        return ssCruxDao.getCrux(testDate, testEnd);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(SsCruxParams ssCruxParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = ssCruxDao.querySsCrux(ssCruxParams);
            List nameList = new ArrayList();
            Calendar c = Calendar.getInstance();
            int weeknum = c.get(Calendar.WEEK_OF_YEAR);
            nameList.add("客户姓名");
            nameList.add("电话");

            nameList.add("测试日期");
            nameList.add("舒张压");
            nameList.add("收缩压");
            nameList.add("身高");
            nameList.add("体重");
            nameList.add("腰围");
            nameList.add("BMI");
            nameList.add("空腹血糖");
            nameList.add("餐后2h血糖");
            nameList.add("糖化血红蛋白");
            nameList.add("丙氨酸氨基转移酶");
            nameList.add("谷草转移酶");
            nameList.add("谷氨酰转移酶");
            nameList.add("脂肪肝");
            nameList.add("甘油三酯");
            nameList.add("胆固醇");
            nameList.add("低密度脂蛋白胆固醇");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("关键指标");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        SsCrux ssCrux = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            ssCrux = (SsCrux) fieldData.get(i);
            // 第四步，创建单元格，并设置值
            String[] nameArry = {ssCrux.getCustomName(), ssCrux.getPhone(), ssCrux.getTestDate(), ssCrux.getDiastolicPressure(), ssCrux.getSystolicPressure(),
                    ssCrux.getHeight(), ssCrux.getWeight(), ssCrux.getWaistline(), ssCrux.getBmi(), ssCrux.getBloodSugar(), ssCrux.getBloodSugar2h(), ssCrux.getHemoglobin(),
                    ssCrux.getAlt(), ssCrux.getGot(), ssCrux.getGgt(), ssCrux.getFattyLiver(), ssCrux.getTriglyceride(), ssCrux.getCholesterol(), ssCrux.getCLdl()};
            for (int j = 0; j < nameArry.length; j++) {
                if (nameArry[j] == null) {
                    row.createCell((short) j).setCellValue("");
                } else {
                    row.createCell((short) j).setCellValue(nameArry[j]);
                }

            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }
        return wb;
    }

    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}